<?php
if(!defined('inside')) die('You do not have permission to execute this file directly.');

/**
* Pagination class file.
*
* @author Federico Ramirez <fedekiller@gmail.com>
* @link http://code.google.com/p/akaikiwi/
* @copyright Copyright &copy; 2008-2011 Federico Ramirez
* @license http://www.opensource.org/licenses/mit-license.php MIT Licence
*/

/*
* This class will generate the links for pagination.
*/
class Pagination {
	private $page = 'page';
	private $pages_to_show = NULL;
	private $limit = NULL;
	private $base = NULL;

	/**
	 * Sets the page name, default is 'page'
	 * @param String $page
	 */
	public  function set_page_name($page) {
		$this->page = $page;
	}

	/**
	 * Sets the number of pages to show
	 * @param integer $pagesToShow
	 */
	public function set_pages_to_show($pagesToShow) {
		$this->pages_to_show = $pagesToShow;
	}

	/**
	 * Sets the limit of entries
	 * @param integer $limit
	 * @param integer $per_page
	 */
	public function set_limit($total, $per_page) {
		$this->limit = ceil($total / $per_page);
	}

	/**
	 * Sets the base url for the links
	 * @param String $base
	 */
	public function set_base($base) {
		$this->base = $base;
	}

	/**
	 * This function returns an string with all the links required for pagination.
	 */
	public function get() {
		if($this->pages_to_show == NULL || $this->limit == NULL || $this->base == NULL) {
			throw new AkaikiwiException('Invalid initialization, you must set: base url, limit and pages to show.');
		}

		AkaiKiwi::loadHelper('urlhelper');
		$page = empty($_GET[$this->page]) ? 1 : $_GET[$this->page];
		$r = NULL;

		if($page > 1) {
			$r = anchor('&laquo; First', $this->base.'/'.$this->page.':1').' '.anchor('<', $this->base.'/'.$this->page.':'.($page - 1)).' ';
		} else {
			$r = '&laquo; First ';
		}

		$start = max(array(1, $page - floor(($this->pages_to_show - 1)/ 2)));
		$finish = max(array($this->pages_to_show, $page + ceil(($this->pages_to_show - 1)/ 2)));
		$finish = min(array($finish, $this->limit));

		for($i = $start; $i <= $finish; $i++) {
			if($page == $i) {
				$r .= $i.' ';
			} else {
				$r .= anchor($i, $this->base.'/'.$this->page.':'.$i).' ';
			}
		}

		if($page < $this->limit) {
			$r .= anchor('>', $this->base.'/'.$this->page.':'.($page + 1)).' '.anchor('Last &raquo;', $this->base.'/'.$this->page.':'.$this->limit);
		} else {
			$r .= 'Last &raquo;';
		}

		return $r;
	}
}
